package com.bobo.demo.Thread.sync;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

//管程法
public class TestPC {

    public static void main(String[] args) {
        SyncContainer container = new SyncContainer();//缓冲区
        new Productor(container).start();
        new Consumer(container).start();
        new Consumer(container).start();
    }


}

//生产者
class Productor extends Thread {

    SyncContainer container;

    public Productor(SyncContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chickren(i),i);
        }
    }
}


//消费者
class Consumer extends Thread {
    SyncContainer container;

    public Consumer(SyncContainer container) {
        this.container = container;
    }

    @Override
    public void run() {

        for (int i = 0; i < 100; i++) {
            container.pop();
        }
    }
}

//缓冲区
class SyncContainer {

    //需要一个容器大小
    Chickren [] chickrens = new Chickren[10];

    int count = 0;//容器内的产品数目

    public SyncContainer() {

    }
    //生产者放入产品
    public synchronized void push(Chickren chickren,Integer i){
        //如果容器满了，需要继续等待
        while(count == chickrens.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果没有满，则添加产品
        chickrens[count] = chickren;
        count++;
        this.notifyAll();//通知消费
        System.out.println("生产了"+i+"只鸡");
        //可以通知消费者消费了
    }

    //消费者消费产品
    public synchronized void pop(){
        //如果容器为空，需要继续等待
        while(count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果可以消费
        count--;
        Chickren chickren = chickrens[count];
        System.out.println(Thread.currentThread().getName()+"消费了---->"+chickren.id+"只鸡");
        this.notifyAll();
    }
}

//产品
@AllArgsConstructor
@NoArgsConstructor
class Chickren {
    int id;
}

